﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SchoolStudentWorkCommon
{
    public static class HttpService
    {
        /// <summary>
        /// 模拟POST或者GET请求
        /// </summary>
        /// <param name="requestUrl">请求的地址</param>
        /// <param name="method">参数</param>
        /// <returns></returns>
        public static string PostService(string requestUrl, string method)
        {
            WebRequest request = WebRequest.Create(requestUrl);
            request.Method = method;
            WebResponse response = request.GetResponse();
            System.IO.Stream str = response.GetResponseStream();
            WebHeaderCollection whc = response.Headers;
            string responsebody = string.Empty;
            using (System.IO.StreamReader srd = new System.IO.StreamReader(str))
            {
                responsebody = srd.ReadToEnd();
            }
            return responsebody;
        }

        /// <summary>
        /// 以JSON格式Post请求服务器
        /// </summary>
        /// <param name="dic">参数字典</param>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public static string PostServiceByJsonType(Dictionary<string, string> dic, string url)
        {
            //最终返回值
            string strText = string.Empty;
            //拼接参数
            var parameter = new StringBuilder();
            var myEncoding = Encoding.GetEncoding("UTF-8");
            foreach (var variable in dic)
            {
                parameter.AppendFormat("{0}={1}", HttpUtility.UrlEncode(variable.Key, myEncoding),
                    HttpUtility.UrlEncode(variable.Value, myEncoding));
                parameter.Append("&");
            }
            parameter.Remove(parameter.Length - 1, 1);

            //实例化HttpWebRequest
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //请求类型
            request.Method = "POST";
            //内容类型
            request.ContentType = "application/x-www-form-urlencoded";
            //字符编码
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(parameter.ToString());
            //内容长度
            request.ContentLength = byteData.Length;
            //请求流
            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }
            //资源响应
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                //拼接最终返回结果
                strText = strText + reader.ReadToEnd();
            }
            //返回
            return strText;
        }
    }
}
